import { ElMessage } from 'element-plus'
import axios from '@/utils/axios'

export function localGet (key) {
  const value = window.localStorage.getItem(key)
  try {
    return JSON.parse(window.localStorage.getItem(key))
  } catch (error) {
    return value
  }
}

export function localSet (key, value) {
  window.localStorage.setItem(key, JSON.stringify(value))
}

export function localRemove (key) {
  window.localStorage.removeItem(key)
}

export const pathMap = {
  index: '首页',
  login: '登录',  
  addQuestions: '录入考试题目',
  addQuestion: '录入单题', 
  square: '试卷广场',
  getQuestionsByKnowledgepoint: '知识点',
  getQuestionsBySection: '节',
  getQuestionsByChapter:'章',
  getQuestionsByCourse: '册',
  automaticGroup: '智能组卷',
  searchQuestion: '搜索结果',
  preludeGroup: "组卷过程",
  jointTestPaper:"地市联考",
  nCEEdetailPoint:"选考细目表",
  addPaper:"录入试卷题目",
  importQuestions:"多题录入",
  testPaper: "试卷选题",
  addPaperByFileStepOne: "第一步",
  addPaperByFileStepTwo: "第二步",
  addPaperByFileStepThree: "第三步",
  addQuestionNoDialoge: "录入单题",
  signin: "注册",
  getQuestionsBypaper:'联考卷选题',
  getQuestionsByGenaralPaper:'原创改编选题',  
  userCenter: '用户中心',
  userInformation: '用户资料',
  changePassword: '修改密码',
  myFavoriteQuestions: '我的收藏',
  addPaperBySelectQuestionList: '填写试卷资料',
  myCreatePaper:'用户中心',
  adminCenter:'审核中心',
  activateAccountManage:'审核中心',
  VIPManage:'审核中心',
  nicknameManage:'审核中心',
  jointPaperManage:'审核中心',
  generalPaperManage:'审核中心',
  notPaperQuestionManage:'审核中心',
  resetPassword: '忘记密码',
  getGuidePapersByKnowledgepoint: '导学案和课件',
  faceRecognition: '人脸识别与分析',
  chatCompletion: 'ai体验馆'
}
// 多张图片上传
// export const uploadImgsServer = 'http://backend-api-02.newbee.ltd/manage-api/v1/upload/files'
// 单张图片上传

// export const uploadImgServer = 'http://localhost:8000/api/uploadImage/'
// export const uploadPaperFileServer = 'http://localhost:8000/api/uploadPaperFileServer/'
// export const uploadFileServer = 'http://localhost:8000/api/uploadFileServer/'
// export const uploadGuidePaperFileServer = 'http://localhost:8000/api/UploadGuidePaperFileServer/'
// export const uploadVocationalPaperFileServer = 'http://localhost:8000/api/uploadVocationalPaperFileServer/'
// export const pdf2wordServer = 'http://localhost:8000/api/Pdf2DocxAPIView/'
// export const image2wordServer = 'http://localhost:8000/api/Image2DocxAPIView/'
// export const faceInspectorServer = 'http://localhost:8000/api/FaceInspectorAPIView/'
// export const baseUrl_noapi='http://localhost:8000/'

export const uploadImgServer = 'https://xxjstk.top/api/uploadImage/'
export const uploadPaperFileServer = 'https://xxjstk.top/api/uploadPaperFileServer/'
export const uploadFileServer = 'https://xxjstk.top/api/uploadFileServer/'
export const uploadVocationalPaperFileServer = 'https://xxjstk.top/api/uploadVocationalPaperFileServer/'
export const uploadGuidePaperFileServer = 'https://xxjstk.top/api/UploadGuidePaperFileServer/'
export const pdf2wordServer = 'https://xxjstk.top/api/Pdf2DocxAPIView/'
export const image2wordServer = 'https://xxjstk.top/api/Image2DocxAPIView/'
export const faceInspectorServer = 'https://xxjstk.top/api/FaceInspectorAPIView/'
export const baseUrl_noapi='https://xxjstk.top/'
export const onlinePreview = 'http://182.61.61.240:8012/onlinePreview?url='

// export const uploadImgServer = 'https://xxjstk.cn/api/uploadImage/'
// export const uploadPaperFileServer = 'https://xxjstk.cn/api/uploadPaperFileServer/'
// export const uploadVocationalPaperFileServer = 'https://xxjstk.cn/api/uploadVocationalPaperFileServer/'
// export const uploadGuidePaperFileServer = 'https://xxjstk.cn/api/UploadGuidePaperFileServer/'
// export const pdf2wordServer = 'https://xxjstk.cn/api/Pdf2DocxAPIView/'
// export const image2wordServer = 'https://xxjstk.cn/api/Image2DocxAPIView/'
// export const faceInspectorServer = 'https://xxjstk.cn/api/FaceInspectorAPIView/'
// export const baseUrl_noapi='https://xxjstk.cn/'

// //网站logo
export const logoUrl = '../assets/logo.png'
// 静态图片前缀
export const imageUrlPrefix = '../assets/'

export function convert_html_2_enter(string) {
  // console.log("换行：",string)
  var reg1 = /<br>/g
  var reg2 = /<p>/g
  var reg3 = /<\/p>/g
  var reg4 = /&nbsp;/g
  var reg5 = /<span(.)*?>/g
  var reg6 = /<\/span>/g
  var reg7 = /\\n/g

  if(reg1.test(string)){
    string=string.replace(reg1, "\n")
  }
  if(reg2.test(string)){
    string=string.replace(reg2, "")
  }
  if(reg3.test(string)){
    string=string.replace(reg3, "\n")
  }
  if(reg4.test(string)){
    string=string.replace(reg4, " ")
  }
  if(reg5.test(string)){
    string=string.replace(reg5, "")
  }
  if(reg6.test(string)){
    string=string.replace(reg6, "")
  }
  if(reg6.test(string)){
    string=string.replace(reg6, "")
  }
  return string
}

export function type_display(value) {
  var display = {0:"简答题", 1:"选择题", 2:"填空题"}
  return display[value]
}
//把插图数组去掉http://ip部分
export function discard_prefix(array){
  // console.log('去掉前缀',array)
  var re = /\/static\/images\/(\w+)\.((jpg)|(jpeg)|(png)|(JPG)|(JPEG)|(PNG))/g
  var pictures = ""
  // console.log("去掉头部的数组为",array) 
  if(array.length==0){
    pictures = ""
  }else if(array.length==1){
    pictures= array[0].match(re)
    pictures=pictures.toString()
  }else{
    let temp_images = []
    for(let item of array){
      let picture= item.match(re)
      temp_images.push(picture)
    }
    pictures=temp_images.join("-")
  }
  return pictures
 }
 //把题目中的content、answer、explain部分的便签转换成后端需要的格式（主要是换行和空格）
 export function convertQuestionFormat(question){
  if("content_front" in question){
    question.content=convert_html_2_enter(question.content_front)
  }else{
    question.content=convert_html_2_enter(question.content)
  }
  if("answer_front" in question){
    question.answer=convert_html_2_enter(question.answer_front)
  }else{
    question.answer=convert_html_2_enter(question.answer)
  }
  if("explain_front" in question){
    question.explain=convert_html_2_enter(question.explain_front)
  }else{
    question.explain=convert_html_2_enter(question.explain)
  }
  question.pictures=discard_prefix(question.images)
  question.pictures_answer = discard_prefix(question.images_answer)
  question.pictures_explain=discard_prefix(question.images_explain)
  return question
 }
 // 删除题目列表中后端新增、修改操作无关的数据项
 export function deleteQuestionItem(question, itemList){
  for(let item of itemList){
    if(item in question){
      delete question[item]
    }    
  }
  return question
 }
// 实现引用对象的深拷贝，即源对象和目标对象互不影响
export function deepClone(obj){
  let objClone = Array.isArray(obj)?[]:{};
  if(obj && typeof obj==="object"){
      for(let key in obj){
          if(obj.hasOwnProperty(key)){
              //判断ojb子元素是否为对象，如果是，递归复制
              if(obj[key]&&typeof obj[key] ==="object"){
                  objClone[key] = deepClone(obj[key]);
              }else{
                  //如果不是，简单复制
                  objClone[key] = obj[key];
              }
          }
      }
  }
  return objClone;
}

//判断当前用户是否管理员，如果是管理员返回true，不是返回false
export function isStaff(){
  let localUser = localGet('user_information')
  return localUser.is_staff == true
}

//给后台发送生成通知
export function createNotification(user_id, content='测试通知'){
  let params = {
    user_id: user_id,
    content: content,
  }
  axios.post(`/NotificationModelViewSet/create_notification/`,params).then(res => {
    console.log("生成通知：", res)
    if (res.code==200){ 
      ElMessage.success("生成通知成功！")
    }else{
        ElMessage.error("生成通知未成功")
        console.log("error", res.message)
    }
  }).catch((error)=>{
    console.log("错误：", error)
  })
}

// 检验token是否有效
export function verifyToken(){
  axios.get('/VerifyToken/').then(res => {
    // console.log('根据令牌', res)
        if (res.code==200){
            localSet('user_information', res.data.results)
            localSet('isLogin', true)
            return true
        }else if(res.code==403){
            ElMessage.warning("你的令牌已过期，请重新登录!")
            router.push('/login')
        }else{
          ElMessage.warning("系统错误，请联系管理员!")
        }
    })
    .catch((error)=>{
        console.log("verifyToken", error)
    })
}
/** 提交用户申请试卷视频解析的权限 */
export const postQuestionVideoPermitAPI = (data) => {
  axios.post(`/questions/create_permit_question_video/`, data).then(res => {
    return res
  }).catch((error)=>{
    console.log("申请视频解析错误：", error)
  })
}
/**读取试题视频申请列表请求 */
export function  getQuestionVideoPermitAPI (data) {
  axios.get('/questions/get_permit_question_video/', {data}).then(res => {
    console.log('get_permit_question_video:', res)
    return res
  }).catch((error)=>{
    console.log("读取试题视频申请列表请求：", error)
  })
}